<template>
  <div class="personnel-config">
    <!-- 人员配置项 -->
    <div v-for="(assignee, idx) in assignees" :key="idx" class="assignee-item">
      <div class="assignee-header">
        <div class="assignee-type-section">
          <!-- 人员类型选择 -->
          <el-select
            v-model="assignee.type"
            size="small"
            class="assignee-type-select"
            :disabled="disabled || isEditLimited"
            @change="onAssigneeTypeChange(idx, $event)"
          >
            <el-option label="用户" value="user" />
            <el-option label="角色" value="role" />
            <el-option label="部门" value="dept" />
            <el-option label="岗位" value="post" />
            <el-option label="发起人" value="starter" />
            <el-option label="发起人部门负责人" value="starterDeptLeader" />
            <el-option label="发起人上级部门负责人" value="starterDeptParentLeader" />
          </el-select>

          <template v-if="['role','user','dept','post'].includes(assignee.type)">
            <!-- 选择按钮 - 根据权限控制显示 -->
            <el-button
              v-if="!isEditDisabled"
              size="small"
              type="primary"
              class="assignee-select-btn"
              :disabled="disabled"
              @click.stop="openSelector(idx, assignee.type)"
              @mousedown.stop
              @mouseup.stop
            >
              <el-icon><Search /></el-icon>
              选择
            </el-button>
            
            <!-- 选择结果直接在选择按钮后面显示 -->
            <div class="assignee-values-inline">
              <template v-if="assignee.type === 'user'">
                <UserInfoTab
                  v-for="(item, i) in assignee.value"
                  :key="i"
                  :userId="item.id"
                  :user-info="item"
                  :show-avatar="true"
                  :show-name="true"
                  :show-account="false"
                  :avatar-size="24"
                  :removable="!disabled && !isEditLimited"
                  @remove="removeAssigneeValue(idx, i)"
                  class="assignee-user-tab"
                />
                <span v-if="!assignee.value || !assignee.value.length" class="empty-selected">
                  未选择用户
                </span>
              </template>
              <template v-else-if="assignee.type === 'role'">
                <el-tag
                  v-for="(item, i) in assignee.value"
                  :key="i"
                  :closable="!disabled && !isEditLimited"
                  @close="removeAssigneeValue(idx, i)"
                  class="assignee-tag role-tag"
                >
                  {{ item.name || item.roleName }}
                </el-tag>
                <span v-if="!assignee.value || !assignee.value.length" class="empty-selected">
                  未选择角色
                </span>
              </template>
              <template v-else-if="assignee.type === 'dept'">
                <el-tag
                  v-for="(item, i) in assignee.value"
                  :key="i"
                  :closable="!disabled && !isEditLimited"
                  @close="removeAssigneeValue(idx, i)"
                  class="assignee-tag dept-tag"
                >
                  {{ item.name || item.deptName }}
                </el-tag>
                <span v-if="!assignee.value || !assignee.value.length" class="empty-selected">
                  未选择部门
                </span>
              </template>
              <template v-else-if="assignee.type === 'post'">
                <el-tag
                  v-for="(item, i) in assignee.value"
                  :key="i"
                  :closable="!disabled && !isEditLimited"
                  @close="removeAssigneeValue(idx, i)"
                  class="assignee-tag post-tag"
                >
                  {{ item.name || item.postName }}
                </el-tag>
                <span v-if="!assignee.value || !assignee.value.length" class="empty-selected">
                  未选择岗位
                </span>
              </template>
            </div>
          </template>
        </div>

        <!-- 删除按钮 - 根据权限控制显示 -->
        <div class="assignee-actions">
          <el-button
            v-if="!isEditDisabled && !isEditLimited"
            size="small"
            type="danger"
            class="assignee-delete-btn"
            :disabled="disabled"
            @click="removeAssignee(idx)"
          >
            <el-icon><Delete /></el-icon>
          </el-button>
        </div>
      </div>

      <!-- 下方：显示具体选择的内容（移除，因为已经在上方显示了） -->
      <div class="assignee-content" v-if="assignee.type && !['role','user','dept','post'].includes(assignee.type)">
        <div class="assignee-static-value">
          {{ getAssigneeTypeLabel(assignee.type) }}
        </div>
      </div>
    </div>

    <!-- 添加人员按钮 - 根据权限控制显示 -->
    <el-button 
      v-if="!isEditDisabled && !isEditLimited"
      size="small" 
      type="primary" 
      :disabled="disabled"
      @click="addAssignee" 
      class="add-assignee-btn"
    >
      <el-icon><Plus /></el-icon>
      添加配置
    </el-button>

    <!-- 人员选择器 -->
    <SelectorModal
      :key="`${selectorType}-${selectorVisible}`"
      v-model:visible="selectorVisible"
      :type="selectorType"
      :multiple="true"
      :selectedList="selectorSelected"
      :original-personnel="originalPersonnel"
      :limited-mode="isEditLimited"
      @update:selectedList="handleSelectorUpdate"
      @close="selectorVisible = false"
    />
  </div>
</template>

<script setup>
import { ref, nextTick, computed } from 'vue'
import { UserInfoTab } from '@/components/UserInfo'
import { Search, Delete, Plus } from '@element-plus/icons-vue'
import SelectorModal from '@/components/Selector/SelectorModal.vue'
import { ElMessage } from 'element-plus'

const props = defineProps({
  assignees: {
    type: Array,
    default: () => []
  },
  // 是否禁用编辑
  disabled: {
    type: Boolean,
    default: false
  },
  // 是否限制模式（只能在现有人员范围内编辑）
  limitedMode: {
    type: Boolean,
    default: false
  },
  // 原始人员配置（用于limited模式下的限制）
  originalPersonnel: {
    type: Array,
    default: () => []
  },
  // 人员编辑权限控制
  personnelEditPermission: {
    type: String,
    default: 'full', // 'disabled' | 'full' | 'limited'
    validator: (value) => ['disabled', 'full', 'limited'].includes(value)
  }
})

const emit = defineEmits(['openSelector', 'update:assignees'])

// 选择器相关状态
const selectorVisible = ref(false)
const selectorType = ref('user')
const selectorSelected = ref([])
const selectorIdx = ref(-1)

// 权限计算属性
const isEditDisabled = computed(() => props.personnelEditPermission === 'disabled')
const isEditLimited = computed(() => props.personnelEditPermission === 'limited')
const isEditFull = computed(() => props.personnelEditPermission === 'full')

/**
 * 添加人员
 */
function addAssignee() {
  if (props.disabled) {
    console.log('PersonnelConfig - 编辑已禁用，无法添加人员')
    return
  }
  
  const newAssignees = [...props.assignees, { type: '', value: [] }]
  emit('update:assignees', newAssignees)
}

/**
 * 删除人员
 */
function removeAssignee(idx) {
  if (props.disabled) {
    console.log('PersonnelConfig - 编辑已禁用，无法删除人员')
    return
  }
  
  const newAssignees = [...props.assignees]
  newAssignees.splice(idx, 1)
  emit('update:assignees', newAssignees)
}

/**
 * 删除人员值
 */
function removeAssigneeValue(idx, i) {
  if (props.disabled) {
    console.log('PersonnelConfig - 编辑已禁用，无法删除人员值')
    return
  }
  
  const newAssignees = [...props.assignees]
  newAssignees[idx] = { ...newAssignees[idx] }
  newAssignees[idx].value = [...newAssignees[idx].value]
  newAssignees[idx].value.splice(i, 1)
  emit('update:assignees', newAssignees)
}

/**
 * 处理人员类型切换
 */
function onAssigneeTypeChange(idx, type) {
  if (props.disabled) {
    console.log('PersonnelConfig - 编辑已禁用，无法修改人员类型')
    return
  }
  
  const newAssignees = [...props.assignees]
  newAssignees[idx] = { ...newAssignees[idx], type: type, value: [] }
  emit('update:assignees', newAssignees)
}

/**
 * 获取人员类型标签
 */
function getAssigneeTypeLabel(type) {
  switch(type) {
    case 'starter': return '发起人';
    case 'starterDeptLeader': return '发起人部门负责人';
    case 'starterDeptParentLeader': return '发起人上级部门负责人';
    default: return type;
  }
}

/**
 * 打开选择器
 */
function openSelector(idx, type) {
  console.log('PersonnelConfig - openSelector called:', { idx, type })
  console.log('props.assignees:', props.assignees)
  console.log('props.disabled:', props.disabled)
  console.log('props.limitedMode:', props.limitedMode)
  console.log('props.originalPersonnel:', props.originalPersonnel)

  // 如果禁用编辑，直接返回
  if (props.disabled) {
    console.log('PersonnelConfig - 编辑已禁用，无法打开选择器')
    return
  }

  selectorIdx.value = idx
  selectorType.value = type
  
  // 确保深拷贝，避免引用问题
  selectorSelected.value = Array.isArray(props.assignees[idx]?.value)
    ? JSON.parse(JSON.stringify(props.assignees[idx].value))
    : []
  console.log('selectorSelected:', selectorSelected.value)

  // 先关闭再打开，触发key变化强制重新渲染
  selectorVisible.value = false
  nextTick(() => {
    selectorVisible.value = true
  })
}

/**
 * 处理选择器更新
 */
function handleSelectorUpdate(selectedList) {
  console.log('PersonnelConfig - handleSelectorUpdate called:', selectedList)
  console.log('props.limitedMode:', props.limitedMode)
  console.log('props.originalPersonnel:', props.originalPersonnel)

  // 如果是限制模式，验证选择的人员是否在原始配置范围内
  if (props.limitedMode && props.originalPersonnel && props.originalPersonnel.length > 0) {
    const originalIds = new Set(props.originalPersonnel.map(person => person.id))
    const invalidSelections = selectedList.filter(person => !originalIds.has(person.id))
    
    if (invalidSelections.length > 0) {
      console.warn('PersonnelConfig - 限制模式下选择了不在原始配置范围内的人员:', invalidSelections)
      // 过滤掉不在原始配置范围内的人员
      const validSelections = selectedList.filter(person => originalIds.has(person.id))
      console.log('PersonnelConfig - 过滤后的有效选择:', validSelections)
      
      // 更新选择器显示
      selectorSelected.value = validSelections
      
      // 如果有效选择为空，提示用户
      if (validSelections.length === 0) {
        ElMessage.warning('只能选择原始配置中的人员')
      }
      
      return
    }
  }

  if (selectorIdx.value >= 0) {
    const newAssignees = [...props.assignees]
    newAssignees[selectorIdx.value] = { ...newAssignees[selectorIdx.value] }
    newAssignees[selectorIdx.value].value = selectedList
    emit('update:assignees', newAssignees)
  }

  selectorVisible.value = false
}
</script>

<style scoped>
.personnel-config {
  width: 100%;
  padding: 8px;
  background: transparent;
}

.assignee-container {
  margin-bottom: 12px;
}

.assignee-item {
  margin-bottom: 12px;
  padding: 12px;
  border: 1px solid #d1d1d1;
  border-radius: 6px;
  background: #f1f1f1;
  transition: all 0.3s ease;
}

.assignee-item:last-child {
  margin-bottom: 0;
}

.assignee-item:hover {
  border-color: #409eff;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.1);
}

.assignee-header {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  gap: 12px;
  margin-bottom: 8px;
}

.assignee-type-section {
  display: flex;
  align-items: center;
  gap: 8px;
  flex: 1;
  flex-wrap: wrap;
}

.assignee-type-select {
  min-width: 100px;
  max-width: 120px;
  flex-shrink: 0;
  height: 32px;
}

.assignee-select-btn {
  min-width: 60px;
  height: 32px;
  padding: 0 12px;
  border-radius: 4px;
  font-weight: 500;
  font-size: 12px;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 4px;
  flex-shrink: 0;
  position: relative;
  z-index: 10;
}

.assignee-select-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 4px rgba(64, 158, 255, 0.2);
}

.assignee-select-btn:active {
  transform: translateY(0);
}

.assignee-actions {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-shrink: 0;
}

.assignee-delete-btn {
  min-width: 28px;
  height: 32px;
  padding: 0;
  border-radius: 4px;
  font-weight: 500;
  font-size: 12px;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
}

.assignee-delete-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 4px rgba(245, 108, 108, 0.2);
}

.count-badge {
  padding: 2px 6px;
  background: #409eff;
  color: #fff;
  border-radius: 10px;
  font-size: 11px;
  font-weight: 600;
  white-space: nowrap;
  height: 20px;
  line-height: 16px;
  display: flex;
  align-items: center;
}

.assignee-content {
  padding: 0;
  margin-left: 0;
}

.assignee-values {
  display: inline-flex;
  flex-wrap: wrap;
  gap: 6px;
  align-items: center;
  min-height: 24px;
  padding: 0;
  margin-left: 0;
  max-width: 100%;
}

/* 新的布局：选择结果在选择按钮后面显示 */
.assignee-item {
  position: relative;
}

.assignee-type-section {
  display: flex;
  align-items: center;
  gap: 8px;
  flex: 1;
  flex-wrap: wrap;
}

.assignee-values-inline {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  flex-wrap: wrap;
  min-height: 32px;
  padding: 0;
  margin-left: 8px;
  max-width: calc(100% - 200px);
}

.assignee-values-inline .assignee-tag {
  margin: 0;
  height: 32px;
  line-height: 30px;
  padding: 0 12px;
  display: inline-flex;
  align-items: center;
  border-radius: 4px;
  font-weight: 500;
  font-size: 12px;
  transition: all 0.3s ease;
}

.assignee-values-inline .assignee-user-tab {
  margin: 0;
  height: 32px;
  display: flex;
  align-items: center;
}

.assignee-values-inline .assignee-user-tab :deep(.user-info-tab) {
  height: 32px;
  line-height: 32px;
}

.assignee-values-inline .assignee-user-tab :deep(.user-avatar) {
  width: 24px;
  height: 24px;
}

.assignee-values-inline .assignee-user-tab :deep(.user-name) {
  line-height: 32px;
  height: 32px;
}

.assignee-values-inline .empty-selected {
  color: #909399;
  font-size: 12px;
  font-style: italic;
  padding: 0 12px;
  background: #f5f5f5;
  border-radius: 4px;
  display: flex;
  align-items: center;
  height: 32px;
}

.assignee-tag {
  margin: 0;
  height: 24px;
  line-height: 22px;
  padding: 0 8px;
  display: inline-flex;
  align-items: center;
  border-radius: 4px;
  font-weight: 500;
  font-size: 12px;
  transition: all 0.3s ease;
}

.assignee-tag:hover {
  transform: translateY(-1px);
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.role-tag {
  background: #e3f2fd;
  border: 1px solid #2196f3;
  color: #1565c0;
}

.dept-tag {
  background: #e8f5e8;
  border: 1px solid #4caf50;
  color: #2e7d32;
}

.post-tag {
  background: #fff8e1;
  border: 1px solid #ff9800;
  color: #ef6c00;
}

.empty-selected {
  color: #909399;
  font-size: 12px;
  font-style: italic;
  padding: 4px 8px;
  background: #f5f5f5;
  border-radius: 4px;
  display: flex;
  align-items: center;
}

.assignee-static-value {
  color: #606266;
  font-size: 12px;
  font-weight: 500;
  padding: 4px 8px;
  background: #f0f0f0;
  border-radius: 4px;
  display: flex;
  align-items: center;
}

.add-assignee-btn {
  width: 100%;
  height: 36px;
  border-radius: 6px;
  font-size: 13px;
  font-weight: 600;
  background: #409eff;
  border: none;
  transition: all 0.3s ease;
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
}

.add-assignee-btn:hover {
  background: #66b1ff;
  transform: translateY(-1px);
  box-shadow: 0 2px 4px rgba(64, 158, 255, 0.3);
}
</style>
